'use strict';

/*
 通用的接口调用类
 author huoyuanyuan
 date 2016/9/23
 */
/**
 * 重新加载数据后刷新ion-content
 */
app.factory('scrollTop', ['$ionicScrollDelegate', function($ionicScrollDelegate) {
	return {
		set: function(id, scrollTop) {
			var view = $ionicScrollDelegate.$getByHandle(id);
			view.resize();
			if(scrollTop) {
				view.scrollTop(true);
			}
		}
	}
}]);
/**
 * 防止软键盘遮挡输入框
 */
app.factory('inputManager', [function() {
	var removePopup = undefined;
	return {
		//打开带确定取消按钮的对话框
		setFocus: function(id) {
			setTimeout(function() {
				document.getElementById(id).scrollIntoViewIfNeeded();
			}, 400);
		},
	}
}]);

//提醒信息弹窗
app.factory('Xalert', ['$ionicLoading', function($ionicLoading) {
	return {
		loading: function(text, time) {
			$ionicLoading.show({
				template: text,
				duration: time == undefined ? 3000 : time,
				noBackdrop: true
			});
		},
		close: function() {
			$ionicLoading.hide();
		}
	}
}]);

//获取设置用户cookies
app.factory("userInfo", function($cookies, $rootScope, $state) {
	var defaultParams = {
		language: 'zh_CN'
	};
	var cookies_name = 'login'; //登录cookie名字
	return {
		get: function(key) {
			return $cookies.get(key);
		},
		//获取登录信息
		getObject: function() {
			var userInfo = $cookies.getObject(cookies_name);
			return userInfo ? userInfo : defaultParams;
		},
		//设置登录信息
		setObject: function(userInfoData) {
			var expireDate = new Date();
			expireDate.setDate(expireDate.getDate() + 365);
			$cookies.putObject(cookies_name, userInfoData, {
				'path': '/',
				'expires': expireDate
			});
			$rootScope.$_userInfo = userInfoData;
		},
		//退出登录
		logout: function() {
			$cookies.remove(cookies_name, {
				'path': '/'
			});
			$cookies.remove("QyWechatOAuth", {
				'path': '/'
			});
			$rootScope.$_userInfo = defaultParams;
			//跳转登录页面
			$state.go('login', {
				timeStamp: new Date().getTime()
			});
		},
		goLogin: function() {
			$state.go("login", {
				timeStamp: new Date().getTime()
			});
		},
		//判断是否登录
		checkLogin: function() {
			var userInfoData = $cookies.getObject(cookies_name) || {};
			
			if(!userInfoData.userid || !userInfoData.token) {
				return false;
			}
			return true;
		},
	}
});
//用户登录鉴权处理
app.factory('Authentication', ['$rootScope', 'userInfo', function($rootScope, userInfo) {
	return {
		authorized: function(event, next) {
			//			var isAuthorized = true;
			var authorizedRoles = next.authorizedRoles || [];
			if(authorizedRoles.length > 0) {
				if(!userInfo.checkLogin()) {
					event.preventDefault();
					userInfo.goLogin();
				}
			}
		},
	};
}]);
//登录过期
app.factory('errorCode', ['userInfo', 'Xalert', function(userInfo, Xalert) {
	return {
		code: function(res) {
			if(res.error_code == 401 || res.error_code == 400) { //身份验证
				userInfo.logout();
				Xalert.loading(res.error_msg);
				event.preventDefault();
				return false;
			}
		}
	}
}]);
//接口数据合并处理
app.factory('interfaceHelps', ['$rootScope', 'ENV', '$cookies', function($rootScope, ENV, $cookies) {
	return {
		//接口的访问地址，开发环境不同请修改env.js
		/*request_url: ENV.apiurl,
		extend_params: function(param) {
			var userInfoData = $rootScope.$_userInfo;
			var nowTime = new Date().getTime() / 1000;
			var params = {
				user_id: userInfoData.user_id ? userInfoData.user_id : '',
				token: userInfoData.token ? userInfoData.token : '',
				device_type: 'PC',
				language: 'zh_CN',
				version: '1.0',
				time_stamp: nowTime
			};
			var results = angular.extend(params, param);
			//alert(angular.toJson(results));
			return results;
		}*/
		request_url: ENV.apiurl,
		extend_params: function(param) {
			var userInfoData = $rootScope.$_userInfo;
		
			var results = angular.toJson(param);
			//console.log(results)
			return results;
		}
	}
}]);
//接口调用
app.factory('getInterface', ['$location', '$http', 'interfaceHelps', 'errorCode', function($location, $http, interfaceHelps, errorCode) {
	return {
		request: function(name) {
			return $location.search()[name] || '';
		},
		//提交数据到后台
		post: function(options, call_back_param) {
			var url = interfaceHelps.request_url + options.module;
			var params = interfaceHelps.extend_params(options.params);
			//console.log(url)
			var token = '';
			if(options.tokenVal == undefined){
				token = '';
			}else{
				token = options.tokenVal;
			}
			//console.log()
			//console.log(a)
			
			/*var params = '&data=';
			options.params = interfaceHelps.extend_params(options.params);
			var url = interfaceHelps.request_url + options.module + params + options.params;
			console.log(url)*/
			$http({
				url: url,
				//withCredentials: true,
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					//'Cookie':'1'
				},
				data: {token:token,"data":params},
				timeout: 1000 * 30
			}).success(function(data, status, header, config) {
				errorCode.code(data);
				call_back_param(data);
			}).error(function(data, status, header, config) {
				call_back_param({
					status: 'N',
					error_msg: "请求失败"
				});
			});
		},
		//从后台获取数据
		jsonp: function(options, call_back_param) {
			//使用stringify将前端传递的对象转化为字符串    data: JSON.stringify(param);
			var params = '&data=';
			options.params = interfaceHelps.extend_params(options.params);
			var url = interfaceHelps.request_url + options.module + params + options.params;
			//console.log(options.params)//字符串
			//console.log(url)
			$http.jsonp(url)
				.success(function(results) {
					errorCode.code(results);
					call_back_param(results);
				})
				.error(function(data, status) {
					call_back_param({
						status: 'N',
						error_msg: "网络不给力"
					});
				});
		},
		jsonpOnly: function(options, call_back_param) {
			
			var url = interfaceHelps.request_url + options.module;
			//console.log(options.module)
			//console.log(url)
			$http.jsonp(url)
				.success(function(results) {
					errorCode.code(results);
					call_back_param(results);
				})
				.error(function(data, status) {
					call_back_param({
						status: 'N',
						error_msg: "网络不给力"
					});
				});
		}
	}
}]);
/*多语言*/
app.filter('i18n', ['languages', function(languages) {
	return function(value, key) {
		if(!value) return '';
		var res = languages[value] || '';
		return key ? res[key] || '' : res;
	};
}]);
//HTML片段转义
app.filter('trustHtml', ['$sce', function($sce) {
	return function(text) {
		return $sce.trustAsHtml(text);
	}
}]);
/**
 * 弹出对话框
 */
app.factory('dialog', ['$ionicPopup', '$ionicLoading', function($ionicPopup, $ionicLoading) {
	var removePopup = undefined;
	return {
		//打开带确定取消按钮的对话框
		openConfirmDialog: function(titleText, leftBtnText, rightBtnText, listener) {
			removePopup = $ionicPopup.show({
				template: '<p style="margin: 2em 0; text-align: center;">' + titleText + '</p>',
				cssClass: 'determineDialog',
				//				scope: $scope,
				buttons: [{
					text: '<font color="#999">' + leftBtnText + '</font>',
					//					type: 'button-positive',
					onTap: function() {
						removePopup = undefined;
						listener.onClickLeft();
					}
				}, {
					text: '<font color="#0082c8">' + rightBtnText + '</font>',
					type: 'button-positive',
					onTap: function(e) {
						listener.onClickRight();
					}
				}]
			})
		},
		//打开弹框，点击背景关闭
		openDiv: function(titleText, leftBtnText, rightBtnText, listener) {
			removePopup = $ionicPopup.show({
				template: '<p style="margin: 2em 0; text-align: center;">' + titleText + '</p>',
				cssClass: 'determineDialog',
				//scope: $scope,
				
				
			})
		},
		//加载数据转圈弹出框
		openLoadingDialog: function() {
			$ionicLoading.show({
				templateUrl: 'apps/templates/loading.html',
				animation: 'fade-in',
				showBackdrop: true,
				maxWidth: 120,
				showDelay: 0
			});
		},
		closeIonIcLoading: function() {
			if(document.getElementById('data-loading')) {
				$ionicLoading.hide();
			}
		},
		//关闭对话框
		closeDialog: function() {
			if(removePopup) {
				removePopup.close();
				removePopup = undefined;
			}
		}
	}
}]);

//图片补全路径
app.filter('baseUrl',['ENV', function(ENV) {
	return function(value) {
		if(!value) return '';
		var url = ENV.domainName;
		if(value) {
			url += value;
		}
		return url;
	};
}]);
//图片补全路径
app.factory('getImageUrl',['ENV', function(ENV) {
	return {
		get: function(value) {
			if(!value) return '';
			var url = ENV.domainName;
			if(value) {
				url += value;
			}
			return url;
		}
	};
}]);
/**
 * 公用方法
 */
app.factory('utils', [function() {
	//上传头像使用
	var compressImage = function(data, config, orientation, callback) {
		var orientation = orientation;
		var sMime = 'png';
		if(window.gIsAndroid && data.indexOf("data:image/") != 0) {
			sMime = sName.split(".").pop().toLowerCase();
			data = data.replace("base64,", "image/" + sMime + ";base64,");
		}
		var img = new Image();
		img.onload = function() {
			var degree = 0,
				drawWidth, drawHeight, width, height;
			drawWidth = this.naturalWidth;
			drawHeight = this.naturalHeight;
			//以下改变一下图片大小
			var maxSide = Math.max(drawWidth, drawHeight);
			if(maxSide > config.maxSize) {
				var minSide = Math.min(drawWidth, drawHeight);
				minSide = minSide / maxSide * config.maxSize;
				maxSide = config.maxSize;
				if(drawWidth > drawHeight) {
					drawWidth = maxSide;
					drawHeight = minSide;
				} else {
					drawWidth = minSide;
					drawHeight = maxSide;
				}
			}
			//resize the image using canvas
			var canvas = document.createElement("canvas");
			canvas.width = width = drawWidth;
			canvas.height = height = drawHeight;
			var ctx = canvas.getContext("2d");
			ctx.drawImage(img, 0, 0);
			//判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
			switch(orientation) {
				//iphone横屏拍摄，此时home键在左侧
				case 3:
					degree = 180;
					drawWidth = -width;
					drawHeight = -height;
					break;
					//iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
				case 6:
					canvas.width = height;
					canvas.height = width;
					degree = 90;
					drawWidth = width;
					drawHeight = -height;
					break;
					//iphone竖屏拍摄，此时home键在上方
				case 8:
					canvas.width = height;
					canvas.height = width;
					degree = 270;
					drawWidth = -width;
					drawHeight = height;
					break;
			}
			//使用canvas旋转校正
			ctx.rotate(degree * Math.PI / 180);
			ctx.drawImage(this, 0, 0, drawWidth, drawHeight);

			//change the dataUrl to blob data for uploading to server
			var dataURL = canvas.toDataURL('image/' + sMime, 1);
			img = null;
			ctx = null;
			canvas = null;
			callback && callback(dataURL);
		};
		img.src = data;
	}

	return {
		//打开带确定取消按钮的对话框
		isNull: function(object) {
			if(object == undefined || object == null || object == "") {
				return true;
			}
			return false;
		},
		isPhone: function(phone) {
			if(phone.indexOf("1") == 0 && phone.length == 11) {
				return true;
			} else {
				return false;
			}
		},
		//判断电话号码是否正确
		checkMobile: function(number) {
			var partten = /^(13[0-9]|14[0-9]|15[0-9]|18[0-9]|17[0-9]|19[0-9]|16[0-9])\d{8}$/i;
			return partten.test(number);
		},
		//上传头像使用
		resizePicture: function(file, config, callbackFunction) {
			try {
				var reader = new FileReader();
				reader.onload = function(e) {
					var orientationT;
					var image = new Image();
					image.onload = function() {
						EXIF.getData(image, function() {
							orientationT = EXIF.getTag(this, 'Orientation');
							compressImage(e.target.result, config, orientationT, function(blob) {
								callbackFunction(blob);
							});
						});
					};
					image.src = e.target.result;
				};
				reader.readAsDataURL(file);
			} catch(e) {
				callbackFunction(e);
			}
		},

	}
}]);

/**
 * 公用方法
 */
app.factory('encryption', [function() {
	/*   
	 *   A   JavaScript   implementation   of   the   Secure   Hash   Algorithm,   SHA-1,   as   defined   
	 *   in   FIPS   PUB   180-1   
	 *   Version   2.1-BETA   Copyright   Paul   Johnston   2000   -   2002.   
	 *   Other   contributors:   Greg   Holt,   Andrew   Kepert,   Ydnar,   Lostinet   
	 *   Distributed   under   the   BSD   License   
	 *   See   http://pajhome.org.uk/crypt/md5   for   details.   
	 */
	/*   
	 *   Configurable   variables.   You   may   need   to   tweak   these   to   be   compatible   with   
	 *   the   server-side,   but   the   defaults   work   in   most   cases.   
	 */
	var hexcase = 0; /*   hex   output   format.   0   -   lowercase;   1   -   uppercase                 */
	var b64pad = ""; /*   base-64   pad   character.   "="   for   strict   RFC   compliance       */
	var chrsz = 8; /*   bits   per   input   character.   8   -   ASCII;   16   -   Unicode             */

	/*   
	 *   These   are   the   functions   you'll   usually   want   to   call   
	 *   They   take   string   arguments   and   return   either   hex   or   base-64   encoded   strings   
	 */
	function hex_sha1(s) {
		return binb2hex(core_sha1(str2binb(s), s.length * chrsz));
	}

	function b64_sha1(s) {
		return binb2b64(core_sha1(str2binb(s), s.length * chrsz));
	}

	function str_sha1(s) {
		return binb2str(core_sha1(str2binb(s), s.length * chrsz));
	}

	function hex_hmac_sha1(key, data) {
		return binb2hex(core_hmac_sha1(key, data));
	}

	function b64_hmac_sha1(key, data) {
		return binb2b64(core_hmac_sha1(key, data));
	}

	function str_hmac_sha1(key, data) {
		return binb2str(core_hmac_sha1(key, data));
	}

	/*   
	 *   Perform   a   simple   self-test   to   see   if   the   VM   is   working   
	 */
	function sha1_vm_test() {
		return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
	}

	/*   
	 *   Calculate   the   SHA-1   of   an   array   of   big-endian   words,   and   a   bit   length   
	 */
	function core_sha1(x, len) {
		/*   append   padding   */
		x[len >> 5] |= 0x80 << (24 - len % 32);
		x[((len + 64 >> 9) << 4) + 15] = len;

		var w = Array(80);
		var a = 1732584193;
		var b = -271733879;
		var c = -1732584194;
		var d = 271733878;
		var e = -1009589776;

		for(var i = 0; i < x.length; i += 16) {
			var olda = a;
			var oldb = b;
			var oldc = c;
			var oldd = d;
			var olde = e;

			for(var j = 0; j < 80; j++) {
				if(j < 16) w[j] = x[i + j];
				else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
				var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
				e = d;
				d = c;
				c = rol(b, 30);
				b = a;
				a = t;
			}

			a = safe_add(a, olda);
			b = safe_add(b, oldb);
			c = safe_add(c, oldc);
			d = safe_add(d, oldd);
			e = safe_add(e, olde);
		}
		return Array(a, b, c, d, e);

	}

	/*   
	 *   Perform   the   appropriate   triplet   combination   function   for   the   current   
	 *   iteration   
	 */
	function sha1_ft(t, b, c, d) {
		if(t < 20) return(b & c) | ((~b) & d);
		if(t < 40) return b ^ c ^ d;
		if(t < 60) return(b & c) | (b & d) | (c & d);
		return b ^ c ^ d;
	}

	/*   
	 *   Determine   the   appropriate   additive   constant   for   the   current   iteration   
	 */
	function sha1_kt(t) {
		return(t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
	}

	/*   
	 *   Calculate   the   HMAC-SHA1   of   a   key   and   some   data   
	 */
	function core_hmac_sha1(key, data) {
		var bkey = str2binb(key);
		if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

		var ipad = Array(16),
			opad = Array(16);
		for(var i = 0; i < 16; i++) {
			ipad[i] = bkey[i] ^ 0x36363636;
			opad[i] = bkey[i] ^ 0x5C5C5C5C;
		}

		var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
		return core_sha1(opad.concat(hash), 512 + 160);
	}

	/*   
	 *   Add   integers,   wrapping   at   2^32.   This   uses   16-bit   operations   internally   
	 *   to   work   around   bugs   in   some   JS   interpreters.   
	 */
	function safe_add(x, y) {
		var lsw = (x & 0xFFFF) + (y & 0xFFFF);
		var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
		return(msw << 16) | (lsw & 0xFFFF);
	}

	/*   
	 *   Bitwise   rotate   a   32-bit   number   to   the   left.   
	 */
	function rol(num, cnt) {
		return(num << cnt) | (num >>> (32 - cnt));
	}

	/*   
	 *   Convert   an   8-bit   or   16-bit   string   to   an   array   of   big-endian   words   
	 *   In   8-bit   function,   characters   >255   have   their   hi-byte   silently   ignored.   
	 */
	function str2binb(str) {
		var bin = Array();
		var mask = (1 << chrsz) - 1;
		for(var i = 0; i < str.length * chrsz; i += chrsz)
			bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
		return bin;
	}

	/*   
	 *   Convert   an   array   of   big-endian   words   to   a   string   
	 */
	function binb2str(bin) {
		var str = "";
		var mask = (1 << chrsz) - 1;
		for(var i = 0; i < bin.length * 32; i += chrsz)
			str += String.fromCharCode((bin[i >> 5] >>> (24 - i % 32)) & mask);
		return str;
	}

	/*   
	 *   Convert   an   array   of   big-endian   words   to   a   hex   string.   
	 */
	function binb2hex(binarray) {
		var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
		var str = "";
		for(var i = 0; i < binarray.length * 4; i++) {
			str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
		}
		return str;
	}

	/*   
	 *   Convert   an   array   of   big-endian   words   to   a   base-64   string   
	 */
	function binb2b64(binarray) {
		var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
		var str = "";
		for(var i = 0; i < binarray.length * 4; i += 3) {
			var triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
			for(var j = 0; j < 4; j++) {
				if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
				else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
			}
		}
		return str;
	}
	var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var encode = function(input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		//			input = _utf8_encode(input);
		while(i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if(isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if(isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
				_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
				_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		return output;
	}
	return {
		//打开带确定取消按钮的对话框
		encryption: function(str) {
			var sha = str_sha1(str);
			var str = encode(sha);
			return str;
		},
	}
}]);
//无数据提示
app.directive('moboNoData', function() {
	return {
		restrict: 'E',
		templateUrl: 'apps/templates/no-data.html',
		scope: {
			icon: '@icon',
			text: '@text',
			layout: '@layout',
			style: '@style',
		}
	}
});
/**
 * 微信js-sdk配置
 * */
app.factory('QyWechat', function($http, $location, $ionicPlatform, $filter, Xalert, $timeout) {
	var signature = function() {
		if($ionicPlatform.isWechat) {
			var urlTest = 'http://' + window.location.host + '/api/index.php/wechat/jssign';

			$http({
				url: urlTest,
				method: 'POST',
				cache: false,
				data: {
					eid: 0,
					url: location.href
				}
			}).success(function(data, status, header, config) {
				wx.ready(function() {});
				wx.error(function(res) {});
				wx.config({
					debug: false,
					appId: data.results.appid,
					timestamp: data.results.timestamp,
					nonceStr: data.results.noncestr,
					signature: data.results.signature,
					jsApiList: [
						'checkJsApi',
						'chooseImage',
						'previewImage',
						'scanQRCode',
						'chooseWXPay'
					]
				});
			}).error(function(data, status, header, config) {

			});

		}
	};
	return {
		init: signature,

		//扫码
		scanQRCode: function(config, callback) {
			wx.scanQRCode({
				needResult: config.needResult || 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
				scanType: config.scanType || ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
				success: function(res) {
					callback && callback(res); // 当needResult 为 1 时，扫码返回的结果
				},
				cancel: function(res) {
					callback && callback(res);
				},
				fail: function(res) {
					callback && callback(res);
				}
			});
		},
		//微信支付请求
		chooseWXPay: function(config, successCallback, cancelCallback) {
			wx.chooseWXPay({
				timestamp: config.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
				nonceStr: config.nonceStr, // 支付签名随机串，不长于 32 位
				package: config.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
				signType: config.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
				paySign: config.paySign, // 支付签名
				success: function() {
					// 支付成功后的回调函数
					successCallback && successCallback();
				},
				cancel: function() {
					cancelCallback && cancelCallback();
				}
			});
		},
		/**
		 * 拍照或者相册
		 * @param {Object} count 最多获取多少张
		 * @param {Object} successCallback
		 * @param {Object} cancelCallback
		 */
		chooseImage: function(count, successCallback, cancelCallback) {
			wx.chooseImage({
				count: count, // 默认9
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
				success: function(res) {
					successCallback && successCallback(res);
				},
				cancel: function() {
					cancelCallback && cancelCallback();
				}
			});
		},
		isIos: function() {
			//微信jssdk
			if(/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
				// alert('---iOS----')
				return true;
			}
			return false;
		},
		isAndroid: function() {
			//微信jssdk
			if(/(Android)/i.test(navigator.userAgent)) {
				// alert('---android----')
				return true;
			}
			return false;
		},
		/**
		 * 照片id转换base64
		 * @param {Object} localId
		 * @param {Object} successCallback
		 * @param {Object} cancelCallback
		 */
		getLocalImgData: function(localId, successCallback, cancelCallback) {
			var i = 0;
			var localData = [];
			localImgData();

			function localImgData() {
				wx.getLocalImgData({
					localId: localId[i], // 图片的localID
					success: function(res) {
						localData.push(res.localData); // localData是图片的base64数据，可以用img标签显示
						if(i == localId.length - 1) {
							successCallback && successCallback(localData);
						} else {
							i++;
							localImgData();
						}
					},
					cancel: function() {
						cancelCallback && cancelCallback(i);
					},
					fail: function() {
						cancelCallback && cancelCallback(i);
					}
				});
			}
		}
	}
});

/**
 * 键值列表接口
 * */
/*app.factory('AppSetValue', ['getInterface', '$http', 'ENV', '$cookies', function(getInterface, $http, ENV, userInfo, $cookies) {
	var factory = {};
	factory.loadSetValue = function(defer) {
		var res_md5 = localStorage.getItem("res_md5");
		var options = {
			module: 'ORDER_DETECTION_SET_VALUE',
			params: {
				value_md5: res_md5 ? res_md5 : ""
			}
		};
		getInterface.jsonp(options, function(results) {
			if(results.status == 'Y') {
				localStorage.setItem("res_md5", results.results.res_md5);
				var res_value = results.results.res_value;
				localStorage.setItem("res_value", angular.toJson(res_value));
				defer.resolve(res_value);
			} else {
				var res_value = localStorage.getItem("res_value");
				if(res_value) {
					res_value = angular.fromJson(res_value);
					defer.resolve(res_value);
				}
			}
		});
	};
	return factory;
}]);*/

//监听列表渲染完成
app.directive('onFinishRenderFilters', function($timeout) {
	return {
		restrict: 'A',
		link: function(scope, element, attr) {
			if(scope.$last === true) {
				$timeout(function() {
					scope.$emit('ngRepeatFinished', element, attr);
				});
			}
		}
	};
});

//调查方向line_dir  
app.directive('lineDir', function() {
    return {
        restrict: 'A',
        replace: true,
        scope: {
        	dir: '=dir'
        },
        template: '<div ng-bind="typeText"></div>',
        controller: function($scope) {
        	// 1:上行 2:下行 3:全幅
			if($scope.dir == 1){
				$scope.typeText = '上行';
			}else if($scope.dir == 2){
				$scope.typeText = '下行';
			}else if($scope.dir == 3){
				$scope.typeText = '全幅';
			}
        }
    };
});

//路面类型pavement_type   
app.directive('pavementType', function() {
    return {
        restrict: 'A',
        replace: true,
        scope: {
        	type: '=type'
        },
        template: '<div ng-bind="typeText"></div>',
        controller: function($scope) {
        	//LQ“沥青路面” SN“水泥路面” SS“砂石路面”
			if($scope.type == 'LQ'){
				$scope.typeText = '沥青路面';
			}else if($scope.type == 'SN'){
				$scope.typeText = '水泥路面';
			}
			//else if($scope.type == 'SS'){
				//$scope.typeText = '砂石路面';
			//}
        }
    };
});
	
//技术等级tech_grade  
app.directive('techGrade', function() {
    return {
        restrict: 'A',
        replace: true,
        scope: {
        	grade: '=grade'
        },
        template: '<div ng-bind="typeText"></div>',
        controller: function($scope) {
        	//0：高速公路 1：一级公路 2：二级公路 3：三级公路 4：四级公路 5：等外公路
			if($scope.grade == 0){
				$scope.typeText = '高速公路';
			}else if($scope.grade == 1){
				$scope.typeText = '一级公路';
			}else if($scope.grade == 2){
				$scope.typeText = '二级公路';
			}else if($scope.grade == 3){
				$scope.typeText = '三级公路';
			}else if($scope.grade == 4){
				$scope.typeText = '四级公路';
			}else if($scope.grade == 5){
				$scope.typeText = '等外公路';
			}
        }
    };
});